package com.arcbbs.service.impl;

import com.arcbbs.constant.BaseConstant;
import com.arcbbs.entity.*;
import com.arcbbs.enums.FileUploadTypeEnum;
import com.arcbbs.exception.BaseException;
import com.arcbbs.mapper.*;
import com.arcbbs.service.FormArticleService;
import com.arcbbs.service.FormBoardService;
import com.arcbbs.service.ForumArticleAttachmentService;
import com.arcbbs.service.UserInfoService;
import com.arcbbs.utils.FileUtils;
import com.arcbbs.utils.StringTools;
import com.arcbbs.utils.SysCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Service
public class ForumArticleAttachmentServiceImpl implements ForumArticleAttachmentService {
    @Resource
    private ForumArticleAttachmentMapper forumArticleAttachmentMapper;
    @Resource
    private ForumArticleAttachmentDownloadMapper forumArticleAttachmentDownloadMapper;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private FormArticleService formArticleService;
    @Resource
    private FormArticleMapper formArticleMapper;
    @Resource
    private UserMessageMapper userMessageMapper;
    @Resource
    private FormBoardService formBoardService;
    @Resource
    private FormBoardMapper formBoardMapper;
    @Autowired
    private FileUtils fileUtils;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public ForumArticleAttachment downloadAttachment(String fileId, SessionWebUserDto sessionWebUserDto) {
        ForumArticleAttachment forumArticleAttachment = forumArticleAttachmentMapper.getbyfileid(fileId);
        //附件是否存在
        if (null == forumArticleAttachment) {
            throw new BaseException("附件不存在");
        }
        //附件是否被下载过，没有下载过的花判断积分够不够
        ForumArticleAttachmentDownload download = null;
        if (forumArticleAttachment.getIntegral() > 0 && !sessionWebUserDto.getUserId().equals(forumArticleAttachment.getUserId())) {
            download = forumArticleAttachmentDownloadMapper.selectbyfileidanduserid(fileId, sessionWebUserDto.getUserId());
            //没有下载过
            if (download == null) {
                UserInfo userInfo = userInfoService.selectbyuserid(sessionWebUserDto.getUserId());
                if (userInfo.getCurrentIntegral() - forumArticleAttachment.getIntegral() < 0) {
                    throw new BaseException("积分不够");
                }
            }
        }
        System.out.println("1233333");
        //没有下载过，新增一条下载记录
        ForumArticleAttachment updateDownload = new ForumArticleAttachment();
        updateDownload.setArticleId(forumArticleAttachment.getArticleId());
        updateDownload.setFileId(fileId);
        updateDownload.setUserId(sessionWebUserDto.getUserId());
        updateDownload.setDownloadCount(1);
        forumArticleAttachmentDownloadMapper.add(updateDownload);
//更新附件下载次数
        forumArticleAttachmentMapper.updatedownloadcount(fileId);
        System.out.println(download);
        //已经下载过或是上传人是自己
        if (download != null || sessionWebUserDto.getUserId().equals(forumArticleAttachment.getUserId())) {
            System.out.println("1234");
            return forumArticleAttachment;
        }
        //扣除下载人积分
        System.out.println(forumArticleAttachment.getIntegral());
        userInfoMapper.updateIntegral(sessionWebUserDto.getUserId(), -forumArticleAttachment.getIntegral());
        System.out.println("扣除");
//附件提供者加分
        userInfoMapper.updateIntegral(forumArticleAttachment.getUserId(), forumArticleAttachment.getIntegral());
        ForumArticleVo forumArticle = formArticleMapper.getbyid(forumArticleAttachment.getArticleId());
        //发消息
        UserMessage userMessage = new UserMessage();
        userMessage.setMessageType(4);
        userMessage.setCreateTime(new Date());
        userMessage.setArticleTitle(forumArticle.getTitle());
        userMessage.setCommentId(0);
        userMessage.setSendUserId(sessionWebUserDto.getUserId());
        userMessage.setSendNickName(sessionWebUserDto.getNickName());
        userMessage.setStatus(1);
        userMessage.setArticleId(forumArticle.getArticleId());
        userMessage.setReceivedUserId(forumArticle.getUserId());
        userMessageMapper.insert(userMessage);
        return forumArticleAttachment;
    }

    @Override
    public void postArticle(HttpSession httpSession, ForumArticle forumArticle, ForumArticleAttachment forumArticleAttachment, MultipartFile cover, MultipartFile attachment) {
        resetBoardInfo(forumArticle);
        String articleId = StringTools.getFinalString(15);
        forumArticle.setArticleId(articleId);
        forumArticle.setPostTime(new Date());
        forumArticle.setLastUpdateTime(new Date());
        if (cover != null) {
            FileUploadDto fileUploadDto = fileUtils.uploadDto(cover, FileUploadTypeEnum.ARTICLE_COVER);
            forumArticle.setCover(fileUploadDto.getLocalpath());
        }
        System.out.println("123333");
        System.out.println(forumArticleAttachment);
        if (attachment != null) {
            System.out.println("执行");
            uploadAttachment(forumArticle, forumArticleAttachment, attachment, true);
        forumArticle.setAttachmentType(1);
        }else{
            forumArticle.setAttachmentType(0);
        }
        System.out.println("1233334");
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        System.out.println("1233335");
        if(sessionWebUserDto.getIsAdmin()==true){
            forumArticle.setStatus(1);
        }else{
            SystemSettingAduitDto aduitDto=SysCacheUtils.getSysSetting().getSystemSettingAduitDto();
            // forumArticle.setStatus(0);
            forumArticle.setStatus(1);

        }
formArticleMapper.insert(forumArticle);
        Integer postIntegral=SysCacheUtils.getSysSetting().getSystemSettingPostDto().getPostIntegral();
        System.out.println(postIntegral+"积分");
  if(postIntegral>0 ){
      userInfoMapper.updateIntegral(sessionWebUserDto.getUserId(),postIntegral);
  }
    }

    private void resetBoardInfo(ForumArticle forumArticle) {
        FormBoard formBoard = formBoardMapper.selectbyid(forumArticle.getPBoardId());
        if (formBoard == null) {
            throw new BaseException("一级板块不存在");
        }
        forumArticle.setPBoardName(formBoard.getBoardName());
        System.out.println(forumArticle.getBoardId()+"forumArticle.getBoardId()");
        if(forumArticle.getBoardId() !=null){
        if (formBoardMapper.selectbyid(forumArticle.getBoardId()) == null) {
            throw new BaseException("二级板块不存在");

         }
            FormBoard formBoard1 = formBoardMapper.selectbyid(forumArticle.getBoardId());

            forumArticle.setBoardName(formBoard1.getBoardName());
        }


    }

    public void uploadAttachment(ForumArticle forumArticle, ForumArticleAttachment forumArticleAttachment, MultipartFile attachment, boolean istrue) {
        Integer allowSizemb = SysCacheUtils.getSysSetting().getSystemSettingPostDto().getAttachmentSize();
        long allowSize = allowSizemb * 1024 * 1024;
        if (attachment.getSize() > allowSize) {
            throw new BaseException("上传的附件过大");
        }
        FileUploadDto fileUploadDto = fileUtils.uploadDto(attachment, FileUploadTypeEnum.ARTICLE_ATTACHMENT);
        forumArticleAttachment.setFileId(StringTools.getFinalString(15));
        forumArticleAttachment.setArticleId(forumArticle.getArticleId());
        forumArticleAttachment.setFileName(fileUploadDto.getOriginalFileName());
        forumArticleAttachment.setFilePath(fileUploadDto.getLocalpath());
        forumArticleAttachment.setFileSize((int) attachment.getSize());
 forumArticleAttachment.setDownloadCount(0);
 forumArticleAttachment.setFileType(4);
 forumArticleAttachment.setUserId(forumArticle.getUserId());
 forumArticleAttachmentMapper.insert(forumArticleAttachment);
    }
}
